<template>
  <div>
    <!-- 头部选项 -->
    <template>
      <header-option>
        <template v-slot:btn>
          <div>
            <cs-btn
              v-if="innerMenu.add.flag"
              type="primary"
              btnText="添加"
              @click.native="addParameterInfo(0, '')"
            />
            <cs-btn v-if="innerMenu.del.flag" btnText="删除" @click.native="dellistfn" />
            <cs-btn btnText="刷新缓存" @click.native="getrefreshCache" />
            <cs-btn v-if="innerMenu.exp.flag" btnText="导出" @click.native="exportfn" />
          </div>
        </template>
        <template v-slot:input>
          <cs-label labelText="参数名称" width="241">
            <el-input class="cs-input" v-model.trim="model.keyword" clearable></el-input>
          </cs-label>
          <el-date-picker
            @change="changetimes"
            class="times"
            v-model="time_quantum"
            type="daterange"
            size="large"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
          <cs-btn type="search" @click.native="searchBtnClick" btnText="查询" class="searcg_btn" />
        </template>
      </header-option>
    </template>

    <!-- 表格 -->
    <template>
      <cs-card>
        <el-table
          v-loading="isLoading"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" :selectable="selected" width="55"></el-table-column>
          <el-table-column prop="name" label="参数名称" width="270"></el-table-column>
          <el-table-column prop="value" label="参数键值" width="200"></el-table-column>
          <el-table-column prop="remark" label="备注">
            <template v-slot="scoped">
              {{ scoped.row.remark ? scoped.row.remark : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template v-slot="scoped">
              {{ scoped.row.createTime ? scoped.row.createTime : '—' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-link
                v-if="innerMenu.upd.flag"
                type="primary"
                class="details"
                @click="addParameterInfo(scope.row.id, scope.row)"
                >编辑
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <div id="pagination_section">
          <span class="currentSelect">{{ `已选${currentSelect}项，共${totalCount}项` }}</span>
          <div class="pagination_right">
            <span>{{ `${pageSize}条/页` }}</span>
            <cs-pagination
              :currentPage="currentPage"
              :totalPage="totalPage"
              @firstPageClick="firstPageClick"
              @previousPageClick="previousPageClick"
              @nextPageClick="nextPageClick"
              @lastPageClick="lastPageClick"
              @junkToOtherPage="junkToOtherPage"
            />
          </div>
        </div>
      </cs-card>
    </template>
    <!-- 添加参数对话框 -->
    <template>
      <el-dialog
        :title="title + '参数信息'"
        :visible.sync="dialogVisible"
        width="808px"
        class="dialogTitle"
        @closed="cancelBtnClick('alterForm')"
      >
        <el-form label-width="120px" ref="alterForm" :model="dialogData" :rules="rules">
          <el-form-item label="参数名称" prop="name">
            <el-input v-model.trim="dialogData.name" :disabled="dialogData.id !== ''"></el-input>
          </el-form-item>
          <el-form-item label="参数键名" prop="code">
            <el-input v-model.trim="dialogData.code" :disabled="dialogData.id !== ''"></el-input>
          </el-form-item>
          <el-form-item label="参数键值" prop="value">
            <el-input v-model.trim="dialogData.value"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <label slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</label>
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              resize="none"
              v-model.trim="dialogData.remark"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <cs-btn
            type="primary"
            @click.native="confirmBtnClick('alterForm')"
            btnText="确定"
            class="confirm_btn dialog_btn"
            :buttonStatus="buttonStatus"
          />
          <cs-btn @click.native="cancelBtnClick('alterForm')" btnText="取消" class="dialog_btn" />
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import _ from 'lodash'

import headerOption from '@/components/headerOption/headerOption.vue'
import csBtn from '@/components/cs-btn/cs-btn.vue'
import csLabel from '@/components/cs-label/cs-label.vue'
import csCard from '@/components/cs-card/cs-card.vue'
import csPagination from '@/components/cs-pagination/cs-pagination.vue'
import {
  getlistDict,
  createDict,
  modifyDict,
  keyDuplicate,
  removeDictByIds,
  refreshCache,
  getexport
} from '@/service/operate/parameter_configure/parameter_configure'
import { getCacheInnerMenu } from '@/utils/menu'

export default {
  components: {
    headerOption,
    csBtn,
    csLabel,
    csCard,
    csPagination
  },
  data() {
    // 自定义校验规则
    const isSiteNumRepeat = async (rule, value, callback) => {
      try {
        if (this.dialogData.id === '') {
          // 查询是否重复
          const { code, data } = await keyDuplicate({ code: value })
          if (code === 0) {
            callback()
          } else {
            callback(new Error('参数键名已存在'))
          }
        }
      } catch (err) {
        console.log(err)
        this.$message.error('服务器出错了')
      }
    }
    return {
      title: '',
      buttonStatus: false,
      model: {
        keyword: '',
        startTime: '',
        endTime: '',
        offset: 1,
        limit: 10
      },
      time_quantum: '',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 当前页码
      currentPage: 1,
      // 一页的条数
      pageSize: 10,
      // 总共多少条数据
      totalCount: 0,
      // 总共多少页
      totalPage: 0,
      currentSelect: 0,
      selectId: [],
      tableData: [],
      dialogVisible: false,
      dialogData: {
        id: '',
        name: '',
        code: '',
        value: '',
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
        code: [
          { required: true, message: '请输入参数键名', trigger: 'blur' },
          { validator: isSiteNumRepeat, trigger: 'blur' }
        ],
        value: [{ required: true, message: '请输入参数键值', trigger: 'blur' }]
      },
      isLoading: false
    }
  },
  watch: {
    'model.keyword'(newValue) {
      if (newValue === '') {
        this.getlist()
      }
    },
    time_quantum(newValue) {
      if (newValue === null) {
        this.getlist()
      }
    }
  },
  created() {
    this.getlist()
    this.innerMenu = getCacheInnerMenu(this.$route.meta.id)
    console.log(this.innerMenu)
  },
  beforeDestroy() {
    // this.$bus.$off('siteSelectNum')
  },
  methods: {
    selected(row, index) {
      if (row.type === null) {
        return true // 不可勾选
      } else if (row.type <= 2) {
        return false
      } else {
        return true // 可勾选
      }
    },
    // 搜索按钮点击事件
    searchBtnClick() {
      // 如果点击搜索时表格还在加载，则不允许发送请求
      if (this.isLoading) return
      this.getlist()
    },
    changetimes(data) {
      if (data) {
        this.model.startTime = data[0]
        this.model.endTime = data[1]
      } else {
        this.model.startTime = ''
        this.model.endTime = ''
      }
    },
    async exportfn() {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const data = await getexport(this.model)
      if (!!data) {
        const filename = '参数配置表.xlsx'
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(filename))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(filename))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
        setTimeout(() => {
          loading.close()
        }, 2000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 2000)
      }
    },
    async getrefreshCache() {
      this.isLoading = true
      const { code, data } = await refreshCache()
      this.isLoading = false
      if (code === 0) {
        this.$message({
          message: '刷新成功',
          type: 'success'
        })
      }
    },
    getlist: _.throttle(async function () {
      this.isLoading = true
      const { code, data } = await getlistDict(this.model)
      this.isLoading = false
      if (code === 0) {
        this.tableData = data.list
        this.currentPage = data.currPage
        this.totalCount = data.totalCount
        this.totalPage = data.totalPage
      }
    }, 1000),
    confirmBtnClick(alterForm) {
      this.buttonStatus = true
      this.$refs[alterForm].validate(async (valid) => {
        if (valid) {
          if (this.dialogData.id === '') {
            const data = await createDict(this.dialogData)
            if (data.code === 0) {
              this.dialogVisible = false
              await this.getlist()
              this.$message({
                message: `${this.title}参数信息成功`,
                type: 'success'
              })
              this.buttonStatus = false
            }
          } else {
            const { code, data } = await modifyDict(this.dialogData)
            if (code === 0) {
              this.dialogVisible = false
              await this.getlist()
              this.$message({
                message: `${this.title}参数信息成功`,
                type: 'success'
              })
              this.buttonStatus = false
            }
          }
        } else {
          console.log('请完成填写')
          this.buttonStatus = false
          return false
        }
      })
    },
    addParameterInfo(id, obj) {
      this.dialogVisible = true
      if (id === 0) {
        this.title = '添加'
      } else {
        this.title = '编辑'
        this.dialogData = {
          id: obj.id,
          name: obj.name,
          code: obj.code,
          value: obj.value,
          remark: obj.remark
        }
      }
    },
    cancelBtnClick(alterForm) {
      this.$refs[alterForm].resetFields()
      this.dialogVisible = false
      this.dialogData = {
        id: '',
        name: '',
        code: '',
        value: '',
        remark: ''
      }
    },
    alterInfoDialogVisible() {},
    deleteInfoDialogVisible() {},
    lastPageClick() {
      if (this.isLoading) return
      this.model.offset = this.totalPage
      this.getlist()
    },
    nextPageClick() {
      if (this.isLoading) return
      this.model.offset = this.currentPage + 1
      this.getlist()
    },
    previousPageClick() {
      if (this.isLoading) return
      this.model.offset = this.currentPage - 1
      this.getlist()
    },
    firstPageClick() {
      if (this.isLoading) return
      this.model.offset = 1
      this.getlist()
    },
    // 跳转页
    junkToOtherPage(page) {
      this.model.offset = page
      this.getlist()
    },
    dellistfn() {
      if (this.selectId.length > 0) {
        const text = '您已选择' + this.currentSelect + '项，确认删除？'
        const _this = this
        this.$confirm(text)
          .then(async () => {
            const { code, data } = await removeDictByIds(this.selectId)
            if (code === 0) {
              if (data) {
                _this.getlist()
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message.error('删除失败')
              }
            }
          })
          .catch((_) => {})
      } else {
        this.$message.error('请勾选后再操作!')
      }
    },
    // 表格选择项变化时触发事件
    selectionChange(selection) {
      this.selectId = []
      // 获取当前选择多少项
      this.currentSelect = selection.length
      // this.$bus.$emit('siteSelectNum', this.currentSelect)
      selection.forEach((item) => {
        this.selectId.push(item.id)
      })
    }
  }
}
</script>

<style scoped>
/* 头部样式start */
.cs-input >>> .el-input__inner {
  width: 152px !important;
  height: 32px !important;
  border-radius: 0 !important;
}

.times {
  margin-right: 20px;
  height: 32px !important;
  line-height: 32px !important;
  padding: 0 4px !important;
  border-radius: 0;
}

.el-input >>> .el-input__icon {
  line-height: 32px;
}

.cs_select >>> .el-input__inner {
  width: 152px;
  height: 32px;
  line-height: 32px;
  border-radius: 0;
}

.creatTimeLabel {
  width: 455px;
}

.el-date-editor >>> .el-input__inner {
  width: 172px;
  height: 32px;
  line-height: 32px !important;
  border-radius: 0;
  padding-left: 16px;
  padding-right: 0;
  color: #939393;
  background-color: #ebeef2;
}

.el-date-editor >>> .el-input__icon {
  line-height: 32px;
}

.selectTimeIcon_middle {
  font-size: 23px;
  color: #e1e1e1;
  padding: 0 5px;
}

.searcg_btn {
  margin-right: 30px;
}

/* 头部样式end */
/* 对话框样式start */

.el-form-item >>> .el-form-item__label {
  padding: 0;
  padding-right: 46px;
  color: #888888;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-textarea >>> .el-textarea__inner {
  border-radius: 0;
}

.dialogTitle >>> .el-dialog {
  padding: 6px 10px 18px 10px !important;
}

/* checkbox样式 */
.el-checkbox >>> .el-checkbox__inner::after {
  top: 0;
  left: 3px;
  border: 3px solid #fff;
  border-left: 0;
  border-top: 0;
  width: 4px;
}

.el-checkbox >>> .el-checkbox__label {
  color: #606266;
}

.el-col {
  height: 40px;
}

/* 对话框样式end */
.el-form-item >>> .el-form-item__label {
  color: #888888;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-textarea >>> .el-textarea__inner {
  border-radius: 0;
}

/* 表格选择框样式start */
.el-table >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.el-table >>> .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
}

.el-table >>> .el-checkbox__inner::before {
  top: 8px;
}

/* 表格选择框样式end */
</style>
